package com.imay.live.fragment.dynamics;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.FrameLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.util.ViewUtil;
import com.imay.live.Constants;
import com.imay.live.R;
import com.imay.live.activity.BaseMainUiActivity;
import com.imay.live.activity.MainActivity2;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.helper.ThreadManager;
import com.imay.live.manager.AccountManager;
import com.imay.live.manager.DataSetListener;
import com.imay.live.fragment.BaseRequestFragment;
import com.imay.live.helper.EventHelper;
import com.imay.live.manager.DataSetManager;
import com.imay.live.manager.DynamicsNotifyManager;
import com.imay.live.model.DynamicsModel2;
import com.imay.live.model.FeedModel;
import com.imay.live.model.RoomInfoModel;
import com.imay.live.model.UserInfoModel;
import com.imay.live.model.UserModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.tbas_api.IMYTBASObject;

import java.util.ArrayList;
import java.util.List;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * Created by chan on 2017/3/25.
 */

public class DynamicsFragment extends BaseRequestFragment implements DynamicsListener, DataSetListener {

    /**
     * ==============  fragment切换状态 ===============
     */
    private int fragmentStatus;

    private final int LINEARFRAGMENTSTATUS = 0;
    private final int GRIDFRAGMENTSTATUS = 1;

    /**
     * ==============  fragment操作状态 ===============
     */
    private int operationStatus;

    private final int DEFAULT = 0;
    private final int REFRESH = 1;
    private final int LOADING = 2;

    /**
     * activity回调fragment
     */
    public static final int ACTION_0 = 0; // 改变activity右边按钮
    public static final int ACTION_1 = 1; // 指定滚动顶部的recyclerView
    public static final int ACTION_2 = 2; // 滚动到顶部并自动刷新
    public static final int ACTION_3 = 3; // 刷新数据,隐藏红点
    public static final int ACTION_4 = 4; // 监听顶栏是否隐藏
    public static final int ACTION_5 = 5; // 判断activity右边按钮
    public static final int ACTION_6 = 6; // 刷新数据,显示红点

    /**
     * 关注与推荐切换
     */
    public static final int ACTION_FOCUS = 100;
    public static final int ACTION_SUGGEST = 101;

    private Context mContext;
    private boolean isLiveCountCall = false;

    // GridFragment 的datas
    private List<Object> entities;
    // LinearFragment 的datas，加上了推荐关注列表
    private List<Object> entitsList;

    /**
     * 用户动态信息
     */
    // 关注用户动态
    private int mBeforeTime = 0;
    private int mMaxId = 0;
    private int mCount = 20;
    // 推荐动态
    private int sinceId = 0;
    private int discount = 30;

    // 更新数据监听
    private IMYTBASObject dynamicsupdate;

    // 推荐
    private boolean suggestStatus = false;
    private int suggectCount = -1;

    /**
     * =============  请求 =================
     */
    private String loadRecommendUserCommand; // 推荐用户
    private String getFeedsRequest; // 获取动态
    private String suggestFeedsRequest; // 推荐动态


    private DynamicsRecall mlinearRecall;
    private DynamicsRecall mgridRecall;

    private FrameLayout mContent;
    private FrameLayout mContent2;

    private boolean isInstance = true;
    private DataSetManager mDataSetManager;

    public static DynamicsFragment newInstance() {
        DynamicsFragment fragment = new DynamicsFragment();
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;

        if (getActivity() instanceof MainActivity2) {
            ((MainActivity2) getActivity()).setDynamicsHandler(mHandler);
        }


        DisplayMetrics display = ViewUtil.getDisplayMetrics(mContext);
        ViewUtil.mScreemWidth = display.widthPixels;
        ViewUtil.mScreemHeight = display.heightPixels;

        entities = new ArrayList<>();
        entitsList = new ArrayList<>();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_dynameics;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mContent = $(R.id.fl_dynameics_content);
        mContent2 = $(R.id.fl_dynameics_content2);
        //loadData();


        loadData();
        initListener();
        mDataSetManager = DataSetManager.Builder.create(this).build();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        com.imay.live.utils.ViewUtil.setForgroundRadius($(R.id.content));
    }

    /**
     * 初始化数据
     *
     * @param list
     */
    private void initDatas(List<Object> list) {
        UserInfoModel userInfo = UserInfoCache.getUserInfo();
        if (userInfo != null) {
            UserInfoModel.StatModel userModel = userInfo.getStat();
            if (userModel != null) {
                if (userModel.getFollow() < 20) { // 推荐人数小于20时，请求推荐关注列表
                    loadRecommendUserCommand = ProtoRequestHelper.task(ProtoHttpFactory.getSuggest(20)).setTag(this.hashCode()).request(this);
                } else { // 推荐人数大于等于20，不请求，直接显示数据
                    suggestStatus = false;
                    if (mlinearRecall != null) {
                        mlinearRecall.setDatas(list);
                    }
                }
            }
        } else {
            suggestStatus = false;
            if (mlinearRecall != null) {
                mlinearRecall.setDatas(list);
            }
        }
    }

    /**
     * 加载动态数据
     */
    private void loadFeed(final int beforeTime, final int maxId, final int count) {
        getFeedsRequest = ProtoRequestHelper.task(ProtoHttpFactory.getFeeds(beforeTime, maxId, count)).setTag(this.hashCode()).request(this);
    }

    /**
     * 获取推荐动态
     */
    private void loadSuggestFeeds(final int sinceId, final int discount) {
        suggestFeedsRequest = ProtoRequestHelper.task(ProtoHttpFactory.getFeedSuggests(sinceId, discount)).setTag(this.hashCode()).request(this);
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        if (command.equals(loadRecommendUserCommand)) { // 推荐关注
            Result<List<UserModel>> result = JSON.parseObject(data, new TypeReference<Result<List<UserModel>>>() {
            }.getType());
            ArrayList<Object> list = new ArrayList<Object>();
            if (result.result == CodeSuccess) {
                suggestStatus = true;
                entitsList.clear();
                entitsList.addAll(entities);
                if (entitsList.size() < suggectCount) {
                    suggectCount = -1;
                    return;
                }
                if (result.data != null && !result.data.isEmpty()) {
                    entitsList.add(suggectCount, result.data);
                }
                list.addAll(entitsList);
                if (mlinearRecall != null) {
                    mlinearRecall.setDatas(list);
                }
            } else {
                list.addAll(entities);
                suggestStatus = false;
                if (mlinearRecall != null) {
                    mlinearRecall.setDatas(list);
                }
                ErrorResult.toastError(mContext, result.result);
            }
        } else if (command.equals(getFeedsRequest)) {
            Result<DynamicsModel2> result = JSON.parseObject(data, new TypeReference<Result<DynamicsModel2>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                // 获取
                int roomCount = result.data.getRooms().size();
                if (isLiveCountCall) {
                    isLiveCountCall = false;
                    if (roomCount != 0) {
                        if (getActivity() instanceof DynamicsNotifyManager.DynamicNotifyListener) {
                            ((DynamicsNotifyManager.DynamicNotifyListener) getActivity()).onLiveNotify(roomCount);
                            return;
                        }
                    }
                }
                int feedCount = result.data.getFeeds().size();
                if (getOperationStatus() == REFRESH || getOperationStatus() == DEFAULT) {
                    setCount(roomCount, feedCount);
                }
                List<Object> list = new ArrayList<Object>();
                list.addAll(result.data.getRooms());
                list.addAll(result.data.getRooms().size(), result.data.getFeeds());
                if (!list.isEmpty()) {
                    setEntities(list);
                } else {
                    if (getOperationStatus() == REFRESH || getOperationStatus() == DEFAULT) {
                        entities.clear();
                        entitsList.clear();
                        if (mlinearRecall != null) {
                            mlinearRecall.loadError("");
                        }
                    }
                }
                datasSet(list);
            } else {
                String error = ErrorResult.getString(mContext, result.result);
                if (mlinearRecall != null) {
                    mlinearRecall.loadError(error);
                    mlinearRecall.setDatas(new ArrayList<>());
                }
            }
            setFinish();
        } else if (command.equals(suggestFeedsRequest)) {
            Result<ArrayList<FeedModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<FeedModel>>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                // 获取
                List<FeedModel> list = new ArrayList<FeedModel>();
                list.addAll(result.data);
                if (!list.isEmpty()) {
                    sinceId = list.get(list.size() - 1).getFeedId();
                    if (mgridRecall != null) {
                        if (getOperationStatus() == REFRESH || getOperationStatus() == DEFAULT) {
                            mgridRecall.setDatas(list);
                        } else if (getOperationStatus() == LOADING) {
                            mgridRecall.addDatas(list);
                        }
                        setFinish();
                        setOperationStatus(DEFAULT);
                    }
                } else {
                    if (getOperationStatus() == REFRESH && mgridRecall != null) {
                        mgridRecall.setDatas(list);
                    }
                    setFinish();
                    setOperationStatus(DEFAULT);
                }
            }
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        if (command.equals(loadRecommendUserCommand)) {
            suggestStatus = false;
            if (mlinearRecall != null) {
                mlinearRecall.setDatas(entities);
            }
        } else if (command.equals(getFeedsRequest) || command.equals(suggestFeedsRequest)) {
            if (operationStatus == REFRESH) {
                if (code != 10001) {
                    String error = ErrorResult.getString(mContext, code);
                    if (mlinearRecall != null) {
                        mlinearRecall.loadError(error);
                    }
                    if (mgridRecall != null) {
                        mgridRecall.loadError(error);
                    }
                } else {
                    if (mlinearRecall != null) {
                        mlinearRecall.netError();
                    }
                    if (mgridRecall != null) {
                        mgridRecall.netError();
                    }
                }
            }
            setFinish();
        }
    }

    private void initListener() {
        // 监听数据改变进行布局刷新 1、评论；2、点赞；3、发表动态
        dynamicsupdate = new IMYTBASObject(false);
        dynamicsupdate.stringCommand = EventHelper.EVENT_DYNAMICS_UPDATE;
        dynamicsupdate.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject imytbasObject) {
                if (!TextUtils.isEmpty(imytbasObject.stringData)) {
                    JSONObject jsonObject = JSON.parseObject(imytbasObject.stringData);
                    int action = jsonObject.getIntValue(Constants.DynamicsUpdate.DYNAMICS_ACTION_KEY);
                    switch (action) {
                        case Constants.DynamicsUpdate.ACTION_DYNAMICE_CREATE:
                            if (entities.size() > mCount) {
                                postEventDataRefresh(entities.size());
                            } else {
                                postEventDataRefresh(mCount);
                            }
                            break;
                    }
                }
            }
        });
        dynamicsupdate.addEventListenWithTBASObject();
    }


    /**
     * 初始化fragment
     */
    private void initFragment() {
        UserInfoModel userModel = UserInfoCache.getUserInfo();
        if (userModel != null) {
            if (userModel.getStat().getFollow() >= 20) {
                changeFragment(ACTION_FOCUS);
            } else {
                changeFragment(ACTION_SUGGEST);
            }
        }
    }

    /**
     * 刷新加载完成
     */
    private void setFinish() {
        if (mlinearRecall != null)
            if (operationStatus == REFRESH) {
                mlinearRecall.setRefreshFinish();
            } else if (operationStatus == LOADING) {
                mlinearRecall.setLoadFinish();
            }
        if (mgridRecall != null)
            if (operationStatus == REFRESH) {
                mgridRecall.setRefreshFinish();
            } else if (operationStatus == LOADING) {
                mgridRecall.setLoadFinish();
            }
        setOperationStatus(DEFAULT);
    }

    /**
     * 有数据的设置
     *
     * @param list
     */
    private void datasSet(List<Object> list) {
        if (isLinearFragmentStatus()) {
            if (getOperationStatus() == REFRESH || getOperationStatus() == DEFAULT) {
                initDatas(list);
            } else if (getOperationStatus() == LOADING) {
                mlinearRecall.addDatas(list);
            }
        }
    }


    /**
     * 归纳相同数据
     *
     * @param list
     */
    private void setEntities(List<Object> list) {
        if (getOperationStatus() == REFRESH || getOperationStatus() == DEFAULT) {
            entities.clear();
            entitsList.clear();
        }
        if (!entities.isEmpty()) {
            Object entity = entities.get(entities.size() - 1);
            if (entity != null) {
                if (entity instanceof FeedModel) {
                    FeedModel feedBean = (FeedModel) entity;
                    Object itemEntity = list.get(list.size() - 1);
                    if (itemEntity instanceof FeedModel) {
                        FeedModel feedBean2 = (FeedModel) itemEntity;
                        if (feedBean.getFeedId() != feedBean2.getFeedId()) {
                            entities.addAll(list);
                            entitsList.addAll(list);
                        }
                    } else {
                        entities.addAll(list);
                        entitsList.addAll(list);
                    }
                } else if (entity instanceof RoomInfoModel) {
                    RoomInfoModel feedBean = (RoomInfoModel) entity;
                    Object itemEntity = list.get(list.size() - 1);
                    if (itemEntity instanceof RoomInfoModel) {
                        RoomInfoModel feedBean2 = (RoomInfoModel) itemEntity;
                        if (feedBean.getTimeStart() != feedBean2.getTimeStart()) {
                            entities.addAll(list);
                            entitsList.addAll(list);
                        }
                    } else {
                        entities.addAll(list);
                        entitsList.addAll(list);
                    }
                }
            } else {
                entities.addAll(list);
                entitsList.addAll(list);
            }
        } else {
            entities.addAll(list);
            entitsList.addAll(list);
        }
    }


    /**
     * 切换线性和格子布局
     */
    public void changeFragment() {
        MobclickAgent.onEvent(getActivity(), "feed_click_layout");
        FragmentTransaction transaction = getChildFragmentManager()
                .beginTransaction();
        if (isLinearFragmentStatus()) {
            setFragmentStatus(GRIDFRAGMENTSTATUS);
            mContent2.setVisibility(View.VISIBLE);
            mContent.setVisibility(View.GONE);
            GridFragment gridFragment = (GridFragment) getChildFragmentManager().findFragmentByTag(GridFragment.class.getName());
            if (gridFragment == null) {
                gridFragment = GridFragment.newInstance();
            }
            if (!gridFragment.isAdded()) {
                transaction.add(R.id.fl_dynameics_content2, gridFragment, LinearFragment.class.getName());
            }
            transaction.show(gridFragment)
                    .commitAllowingStateLoss();
            getChildFragmentManager().executePendingTransactions();
            if (entities != null && !entities.isEmpty()) {
                List<Object> list = new ArrayList<>();
                list.addAll(entities);
                mgridRecall.setDatas(list);
            }
            setSmoothToTopView(gridFragment.getRecyclerView());
        } else {
            setFragmentStatus(LINEARFRAGMENTSTATUS);
            mContent.setVisibility(View.VISIBLE);
            mContent2.setVisibility(View.GONE);
            LinearFragment linearFragment = (LinearFragment) getChildFragmentManager().findFragmentByTag(LinearFragment.class.getName());
            if (linearFragment == null) {
                linearFragment = LinearFragment
                        .newInstance();
            }
            if (!linearFragment.isAdded()) {
                transaction.add(R.id.fl_dynameics_content, linearFragment, LinearFragment.class.getName());
            }
            transaction.show(linearFragment)
                    .commitAllowingStateLoss();
            getChildFragmentManager().executePendingTransactions();
            if (entitsList != null && !entitsList.isEmpty()) {
                List<Object> list = new ArrayList<>();
                list.addAll(entitsList);
                mlinearRecall.setDatas(list);
            }
            setSmoothToTopView(linearFragment.getRecyclerView());
        }
    }

    /**
     * 切换关注以及推荐列表
     */
    public void changeFragment(int action) {
        MobclickAgent.onEvent(getActivity(), "feed_click_layout");
        FragmentTransaction transaction = getChildFragmentManager()
                .beginTransaction();
        if (getActivity() instanceof BaseMainUiActivity) {
            ((BaseMainUiActivity) getActivity()).setTitleCurrentItem(action);
        }
        if (action == ACTION_SUGGEST) {
            setFragmentStatus(GRIDFRAGMENTSTATUS);
            mContent2.setVisibility(View.VISIBLE);
            mContent.setVisibility(View.GONE);
            GridFragment gridFragment = (GridFragment) getChildFragmentManager().findFragmentByTag(GridFragment.class.getName());
            if (gridFragment == null) {
                gridFragment = GridFragment.newInstance();
            }
            if (!gridFragment.isAdded()) {
                transaction.add(R.id.fl_dynameics_content2, gridFragment, GridFragment.class.getName());
            }
            if (mlinearRecall != null) {
                mlinearRecall.stop();
            }
            transaction.show(gridFragment)
                    .commitAllowingStateLoss();
            getChildFragmentManager().executePendingTransactions();
            if (sinceId == 0) {
                refreshData();
            }
            setSmoothToTopView(gridFragment.getRecyclerView());
        } else if (action == ACTION_FOCUS) {
            setFragmentStatus(LINEARFRAGMENTSTATUS);
            mContent.setVisibility(View.VISIBLE);
            mContent2.setVisibility(View.GONE);
            LinearFragment linearFragment = (LinearFragment) getChildFragmentManager().findFragmentByTag(LinearFragment.class.getName());
            if (linearFragment == null) {
                linearFragment = LinearFragment
                        .newInstance();
            }
            if (!linearFragment.isAdded()) {
                transaction.add(R.id.fl_dynameics_content, linearFragment, LinearFragment.class.getName());
            }
            if (mlinearRecall != null) {
                mlinearRecall.play();
            }
            transaction.show(linearFragment)
                    .commitAllowingStateLoss();
            getChildFragmentManager().executePendingTransactions();
            if (entitsList.isEmpty()) {
                refreshData();
            }
            setSmoothToTopView(linearFragment.getRecyclerView());
        }
    }

    @Override
    public void scrollToPosition(int position) {
//        if (getActivity() instanceof MainActivity2) {
//            ((MainActivity2) getActivity()).changeRightIv(isLinearFragmentStatus());
//        }
        //changeFragment();
        if (mlinearRecall != null) {
            int p = position;
            if (suggestStatus) {
                if (p >= suggectCount) {
                    p = p + 1;
                }
            }
            mlinearRecall.scrollToPosition(p);
        }
    }

    @Override
    public void loadMore() {
        setOperationStatus(LOADING);
        if (isLinearFragmentStatus()) { // 判断是关注动态
            if (!entities.isEmpty()) {
                Object itemEntity = entities.get(entities.size() - 1);
                if (itemEntity instanceof RoomInfoModel) {
                    RoomInfoModel bean = (RoomInfoModel) itemEntity;
                    loadFeed(mBeforeTime, bean.getTimeStart(), mCount);
                } else if (itemEntity instanceof FeedModel) {
                    FeedModel bean = (FeedModel) itemEntity;
                    loadFeed(mBeforeTime, bean.getFeedId(), mCount);
                }
            }
        } else {
            loadSuggestFeeds(sinceId, discount);
        }
    }

    /**
     * 刷新
     */
    @Override
    public void refreshData() {
        setOperationStatus(REFRESH);
        if (isLinearFragmentStatus()) { // 判断是关注动态
            mMaxId = 0;
            loadFeed(mBeforeTime, mMaxId, mCount);
            ((MainActivity2) getActivity()).hideRedPoint();
        } else { // 判断是推荐动态
            sinceId = 0;
            loadSuggestFeeds(sinceId, discount);
        }
    }

    /**
     * 监听数据刷新对应条数
     *
     * @param count
     */
    public void postEventDataRefresh(int count) {
        setOperationStatus(DEFAULT);
        loadFeed(mBeforeTime, mMaxId, count);
    }


    public void setSpringViewEnable(boolean springViewEnable) {
        if (mlinearRecall != null) {
            mlinearRecall.setSpringViewEnable(springViewEnable);
        }
        if (mgridRecall != null) {
            mgridRecall.setSpringViewEnable(springViewEnable);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dynamicsupdate != null) {
            dynamicsupdate.destroy();
        }
        if (mDataSetManager != null) {
            mDataSetManager.unregisterDataNotify();
        }
    }


    /**
     * 推荐用户放在动态的第5个位置
     *
     * @param roomCount
     * @param feedCount
     */
    public void setCount(int roomCount, int feedCount) {
        if (feedCount < 6) {
            suggectCount = roomCount + feedCount;
        } else {
            suggectCount = roomCount + 5;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        // 友盟统计页面跳转，重写此方法，可以保证ViewPager切换Fragment时能够准确的记录Fragment之间的跳转
        // 不用再调用Fragment的生命周期方法
        if (isVisibleToUser) {
            MobclickAgent.onEvent(getActivity(), "feed_open");
            MobclickAgent.onPageStart(getClass().getSimpleName());
        } else {
            MobclickAgent.onPageEnd(getClass().getSimpleName());
        }


        if (mlinearRecall == null) {
            return;
        }
        if (isVisibleToUser) {
            mlinearRecall.play();
        } else {
            mlinearRecall.stop();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mlinearRecall != null) {
            if (((MainActivity2) getActivity()).getShow() == 0) {
                mlinearRecall.play();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mlinearRecall != null) {
            mlinearRecall.stop();
        }
    }

    private boolean isLinearFragmentStatus() {
        return this.fragmentStatus == LINEARFRAGMENTSTATUS;
    }

    public void setFragmentStatus(int fragmentStatus) {
        this.fragmentStatus = fragmentStatus;
    }

    public int getOperationStatus() {
        return operationStatus;
    }

    public void setOperationStatus(int operationStatus) {
        this.operationStatus = operationStatus;
    }

    public Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case ACTION_0: // 改变activity右边按钮
//                    if (getActivity() instanceof MainActivity2) {
//                        ((MainActivity2) getActivity()).changeRightIv(isLinearFragmentStatus());
//                    }
                    //changeFragment();
                    break;
                case ACTION_1: // 指定滚动顶部的recyclerView
                    if (isLinearFragmentStatus()) {
                        if (mlinearRecall != null) {
                            if (mlinearRecall.getRecyclerView() != null) {
                                setSmoothToTopView(mlinearRecall.getRecyclerView());
                            }
                        }
                    } else {
                        if (mgridRecall != null) {
                            if (mgridRecall.getRecyclerView() != null) {
                                setSmoothToTopView(mgridRecall.getRecyclerView());
                            }
                        }
                    }
                    break;
                case ACTION_2: // 滚动到顶部并自动刷新
                    if (isLinearFragmentStatus()) {
                        if (mlinearRecall != null) {
                            mlinearRecall.scrolltoTop();
                        }
                    } else {
                        if (mgridRecall != null) {
                            mgridRecall.scrolltoTop();
                        }
                    }
                    break;
                case ACTION_3: // 刷新数据
                    isLiveCountCall = false;
                    refreshData();
                    break;
                case ACTION_4: // 监听顶栏是否隐藏
                    if (mlinearRecall != null) {
                        mlinearRecall.appLayoutStatus((Boolean) msg.obj);
                    }
                    break;
                case ACTION_5: // 判断activity右边按钮
//                    if (getActivity() instanceof MainActivity2) {
//                        ((MainActivity2) getActivity()).changeRightIv(!isLinearFragmentStatus());
//                    }
                    break;
                case ACTION_6:
                    isLiveCountCall = true;
                    if (entities != null && !entities.isEmpty()) {
                        postEventDataRefresh(entities.size());
                    } else {
                        postEventDataRefresh(mCount);
                    }
                    break;
                case ACTION_FOCUS:
                case ACTION_SUGGEST:
                    changeFragment(msg.what);
                    break;
            }
        }
    };

    public void setLinearRecall(DynamicsRecall linearRecall) {
        mlinearRecall = linearRecall;
    }

    public void setGridRecall(GridFragment gridRecall) {
        mgridRecall = gridRecall;
    }

    @Override
    public void loadData() {
        if (isCreate) {
            if (AccountManager.getInstance().isLogined()) {
                if (isInstance) {
                    isInstance = false;
                    ThreadManager.post(ThreadManager.THREAD_UI, new Runnable() {
                        @Override
                        public void run() {
                            initFragment();
                        }
                    });
                }
            }
        }
    }

    @Override
    public void clearData() {
        if (entities != null) {
            entities.clear();
        }
        if (entitsList != null) {
            entitsList.clear();
        }
        if (mlinearRecall != null) {
            mlinearRecall.setDatas(new ArrayList<>());
        }
        if (mgridRecall != null) {
            mgridRecall.setDatas(new ArrayList<>());
        }
        sinceId = 0;
        isInstance = true;
    }
}
